package cn.ctyun.videoplayer.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;

import com.danikula.videocache.CacheListener;
import com.danikula.videocache.HttpProxyCacheServer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.ctyun.videoplayer.player.IjkVideoView;
import cn.ctyun.videoplayer.util.HttpUtils;
import cn.ctyun.videoplayer.util.VideoCacheManager;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

// TODO: 不使用这种方式缓存视频
public class CacheIjkVideoView extends IjkVideoView {

    public static final String TAG = CacheIjkVideoView.class.getSimpleName();

    protected HttpProxyCacheServer mCacheServer;
    protected int mBufferedPercentage;
//    protected boolean mIsCacheEnabled = true; //默认打开缓存

    public CacheIjkVideoView(@NonNull Context context) {
        super(context);
    }

    public CacheIjkVideoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CacheIjkVideoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

//    private long lastLength = 0;
//    M3U8DownloadTask task1 = new M3U8DownloadTask("1001");

//    private String contentType;

    @Override
    protected void startPrepare(boolean needReset) {
//        super.startPrepare(needReset);
        if (TextUtils.isEmpty(mCurrentUrl) && mAssetFileDescriptor == null) return;
        if (needReset) mMediaPlayer.reset();
        if (mAssetFileDescriptor != null) {
            mMediaPlayer.setDataSource(mAssetFileDescriptor);
            //本地文件不能缓存
        } else if (mPlayerConfig.enableCache && !mCurrentUrl.startsWith("file://")) {

            HttpUtils.sendOkHttpRequest(mCurrentUrl, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    CacheIjkVideoView.this.mAttachActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mCacheServer = getCacheServer();
                            String proxyPath = mCacheServer.getProxyUrl(mCurrentUrl);
                            mCacheServer.registerCacheListener(cacheListener, mCurrentUrl);
                            if (mCacheServer.isCached(mCurrentUrl)) {
                                mBufferedPercentage = 100;
                            }
                            mMediaPlayer.setDataSource(proxyPath, mHeaders);
                            mMediaPlayer.prepareAsync();
                            setPlayState(STATE_PREPARING);
                            setPlayerState(isFullScreen() ? PLAYER_FULL_SCREEN : PLAYER_NORMAL);
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String contentType =  response.header("Content-Type");
                    Log.d(TAG, "Content-Type : " + contentType);

                    CacheIjkVideoView.this.mAttachActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //m3u8文件，暂不支持离线缓存
                            if (contentType != null && contentType.toLowerCase().contains("x-mpegurl")) {
                                mMediaPlayer.setDataSource(mCurrentUrl, mHeaders);
                                mMediaPlayer.prepareAsync();
                                setPlayState(STATE_PREPARING);
                                setPlayerState(isFullScreen() ? PLAYER_FULL_SCREEN : PLAYER_NORMAL);
                            } else {
                                mCacheServer = getCacheServer();
                                String proxyPath = mCacheServer.getProxyUrl(mCurrentUrl);
                                mCacheServer.registerCacheListener(cacheListener, mCurrentUrl);
                                if (mCacheServer.isCached(mCurrentUrl)) {
                                    mBufferedPercentage = 100;
                                }
                                mMediaPlayer.setDataSource(proxyPath, mHeaders);
                                mMediaPlayer.prepareAsync();
                                setPlayState(STATE_PREPARING);
                                setPlayerState(isFullScreen() ? PLAYER_FULL_SCREEN : PLAYER_NORMAL);
                            }
                        }
                    });


                }
            });

        } else {
            mMediaPlayer.setDataSource(mCurrentUrl, mHeaders);
            mMediaPlayer.prepareAsync();
            setPlayState(STATE_PREPARING);
            setPlayerState(isFullScreen() ? PLAYER_FULL_SCREEN : PLAYER_NORMAL);
        }
    }


    public HttpProxyCacheServer getCacheServer() {
        return VideoCacheManager.getProxy(getContext().getApplicationContext());
    }

//    /**
//     * 是否打开缓存，默认打开
//     */
//    public void setCacheEnabled(boolean isEnabled) {
//        mIsCacheEnabled = isEnabled;
//    }

    /**
     * 开启缓存后，返回是缓存的进度
     */
    @Override
    public int getBufferedPercentage() {
        return mPlayerConfig.enableCache ? mBufferedPercentage : super.getBufferedPercentage();
    }

    @Override
    public void release() {
        super.release();
        if (mCacheServer != null) {
            mCacheServer.unregisterCacheListener(cacheListener);
            cacheListener = null;
        }
    }

    /**
     * 缓存监听
     */
    private CacheListener cacheListener = new CacheListener() {
        @Override
        public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
            mBufferedPercentage = percentsAvailable;
        }
    };

    public String parseIndex(String url, String toFile) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        if (conn.getResponseCode() == 200) {
            String realUrl = conn.getURL().toString();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));


            File newFile = new File(toFile);
            FileWriter write = new FileWriter(newFile, true);
            BufferedWriter bufferedWriter = new BufferedWriter(write);

            String line;
//            mCacheServer = getCacheServer();
            HttpProxyCacheServer cacheServer = VideoCacheManager.newProxy(getContext().getApplicationContext());
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("#")) {

                } else {
                    cacheServer.registerCacheListener(new CacheListener() {
                        @Override
                        public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
                            mBufferedPercentage = percentsAvailable;
                        }
                    }, line);
                    line = cacheServer.getProxyUrl(line);
                }
                bufferedWriter.write(line);
                bufferedWriter.newLine();//换行
                bufferedWriter.flush();

            }
            reader.close();
            write.close();
            bufferedWriter.close();

            return toFile;

        }

        return null;
    }
}
